<?php

namespace app\common\services;
use app\common\model\Attachment;
use think\Env;

class UrlService
{
    /**
     * @param string $uri
     * @param string $type
     * @return string
     */
    public static function getFileUrl_bak($uri = '', $type = '')
    {
        if (empty($uri)) {
            return '';
        }
        if (strstr($uri, 'http://') || strstr($uri, 'https://')) {
            return $uri;
        }
        
        if ($uri && $uri !== '/' && substr($uri, 0, 1) !== '/') {
            $uri = '/' . $uri;
        }
        
        $domain = Env::get('app.url');

        return $domain . $uri;
    }


    public static function getFileUrl($url, $domain = false){

        if(!$url) return '';
        if($at=Attachment::where('url',$url)->find()){
            if($at['storage'] == 'local'){
                return request()->domain().$url;
            }
        }
        try {
            $config = get_addon_config('alioss');
            $configs = get_addon_info('alioss');
        }catch (\Exception $e){
            $config = [];
            $configs = ['state'=>0];
        }

        if($configs['state'] == 1){
            if(strpos($url,'://') === false){
                if($url[0] == '/'){
                    return $config['cdnurl'].$url;
                }
                return $config['cdnurl'].'/'.$url;
            }
        }
        $old_url = $url;
        $regex  = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $cdnurl = \think\Config::get('upload.cdnurl');
        if (is_bool($domain) || stripos($cdnurl, '/') === 0) {
            $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
        }
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $new_url = $domain . $url;
        }

        if (($info = @getimagesize($url)) !== false) {
            return $url;
        } else {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $old_url;
        }

        return $url;

        

        $old_url = $url;

        $regex   = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $cdnurl  = \think\Config::get('upload.cdnurl');
    
        if (is_bool($domain) || stripos($cdnurl, '/') === 0) {
            $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
        }

        if (($info = @getimagesize($url)) !== false) {
            return $url;
        } else {
            $domain = Env::get('app.url');
            $url = $domain . $old_url;
        }
   
        return $url;
    }
    
}